package com.silences.servlet;

import com.alibaba.fastjson.JSON;
import com.silences.pojo.Doods;
import com.silences.service.DoodsService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.util.Map;


@WebServlet("/doods")
public class DoodsServlet extends HttpServlet {
    //创建对象
    DoodsService doodsService = new DoodsService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //乱码问题统一解决
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //
        String method =req.getParameter("method");
        if(method.equals("getDoodss")){
            getDoodss(req,resp); //获取商品裂帛啊
        }else if(method.equals("getDoods")){
            getDoods(req,resp);//获取单个商品裂帛啊
        }else if(method.equals("addDoods")){
            addDoods(req,resp);
        }
    }


    private void addDoods(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String name =req.getParameter("name");
        String type =req.getParameter("type");
        String price= req.getParameter("price");
        String quantity= req.getParameter("quantity");
        String status =req.getParameter("status");
        String info =req.getParameter("info");
        Doods doods = new Doods(0,name,type,price,Integer.parseInt(quantity),status,info);
        Map<String,Object> map= doodsService.addDoods(doods);
        resp.getWriter().write(JSON.toJSON(map).toString()); //造成列表渲染格式是换成17.21.46
                                                             //response.getWriter().write(JSON.toJSONStringWithDateFormat(map,"yyyy-MM-dd HH:mm:ss",SerializerFeature.WriteDateUseDateFormat).toString())
    }


    private void getDoodss(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String searchname = req.getParameter("searchname");
        String pageIndex= req.getParameter("pageIndex");
        String pageSize = req.getParameter("pageSize");
        Map<String,Object> map = doodsService.getDoodss(searchname,
                Integer.parseInt(pageIndex), Integer.parseInt(pageSize));
        resp.getWriter().write(JSON.toJSON(map).toString());
    }

    private void getDoods(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String id =req.getParameter("id");
        Map<String,Object> map = doodsService.getDoods( Integer.parseInt(id));
        resp.getWriter().write(JSON.toJSON(map).toString());
    }
}
